package com.itheima.accountingdb.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.accountingdb.mapper.CategoryMapper;
import com.itheima.accountingdb.pojo.Category;
import com.itheima.accountingdb.pojo.PageBean;
import com.itheima.accountingdb.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * @author panweiwei
 */
@Service
public class CategoryServiceImpl implements CategoryService {
    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public Category add(Category category) {
        category.setUserId(String.valueOf(1));
        category.setIsDeleted(String.valueOf(0));
        category.setCreatedAt(String.valueOf(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))));
        int rows = categoryMapper.add(category);
        if (rows <= 0) {
            return null;
        }
        return category;
    }

    @Override
    public int update(long id, String name , String type) {
        Category category = new Category();
        category.setUpdatedAt(String.valueOf(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))));
        category.setName(name);
        category.setType(type);
        category.setId(id);
        int rows = categoryMapper.update(category);
        return rows;
    }

    @Override
    public int delete(Long id) {
        if (id != null) {
            int rows = categoryMapper.delete(id);
            return rows;
        }
        return 0;
    }

    @Override
    public PageBean<Category> list(Integer page, Integer size, String name, String type, Long isDeleted, Long userId) {
        PageBean<Category> pageBean = new PageBean<>();
        //开始分页查询
        PageHelper.startPage(page, size);
        List<Category> categoryLista = categoryMapper.list(page, size, name, type, isDeleted,userId);
        Page<Category> categoryPage = (Page<Category>) categoryLista;
        pageBean.setTotal(categoryPage.getTotal());
        pageBean.setItems(categoryPage.getResult());
        return pageBean;
    }

}
